<?php
namespace app\index\controller;

class Goods extends Base
{
    public function index($id)
    {
        //商品基本信息
        $goodsRes = db('tp_goods')->alias('g')
            ->field('g.*,IFNULL(sum(og.goods_num),0) xl,  IFNULL((select count(goods_id) from tp_comment c where c.goods_id=g.id),0) pl')
            ->join('tp_order_goods og', 'g.id = og.goods_id And og.order_id IN (select id from tp_order where pay_status=1)', 'LEFT')
            ->where(array('g.id'=>$id))->group('g.id')->find();
        //商品相册的信息
    	$goodsPhoto=db('tp_goods_photo')->where(array('goods_id'=>$id))
    	->field('og_photo,sm_photo,mid_photo,big_photo')->select();

    	$goodsThumb=array();
    	$goodsThumb['og_photo']=$goodsRes['or_thumb'];
    	$goodsThumb['sm_photo']=$goodsRes['sm_thumb'];
    	$goodsThumb['mid_photo']=$goodsRes['mid_thumb'];
    	$goodsThumb['big_photo']=$goodsRes['big_thumb'];
    	//把主图插入商品相册中
    	array_unshift($goodsPhoto,$goodsThumb);
    	
    	
        //获取商品属性
        $goodsAttrArr=db('tp_goods_attr')->alias('ga')->field('ga.*,a.attr_name,a.attr_type')->join('tp_attr a','ga.attr_id=a.id')->where(array('goods_id'=>$id))->select();
        $radioAttrArr=array();
        $uniAttrArr=array();
        foreach ($goodsAttrArr as $k => $v) {
            if($v["attr_type"]==1){//单选属性
                $radioAttrArr[$v['attr_name']][]=$v;
            }else{//唯一属性
                $uniAttrArr[]=$v;
            }
        }


        //上级分类信息
        //面包屑导航
        if(cache('position')){
            $position=cache('position');
        }else{
            $position=model('TpCategory')->position($goodsRes['category_id']);
            if($this->configs['cache_button']=='是'){
                cache('position', $position,$this->configs['cache_time']);//设置缓存

            }

        }
        foreach($position as $k=>$v){

            $position[$k]['children']=db('tp_category')->where('pid',$v['id'])->select();

        }
//        print_r($position);die;



    	$this->assign([
    		'goodsRes'=>$goodsRes,
    		'goodsPhoto'=>$goodsPhoto,
            'radioAttrArr'=>$radioAttrArr,
            'uniAttrArr'=>$uniAttrArr,
            'position'=>$position
    	]);
        return view('goods');
    }

    //ajax获取商品的会员价格
    public function ajaxGetMemberPrice(){
        $data=input('post.');
        $goods_id=$data['goods_id'];
        $_goodsAttrIds=$data['goodsAttrIds'];
        $goodsAttrIds=[];
        $goodsAttrIds=explode(',', $_goodsAttrIds);
        $attrPrices=0;
        foreach ($goodsAttrIds as $k => $v) {
            $attr=db('tp_goods_attr')->field('attr_price')->where(array('id'=>$v))->find();
            $attrPrices=$attrPrices+intval($attr['attr_price']);
            
        }
        $memberPrice=model('TpGoods')->getMemberPrice($goods_id);
        $price=$memberPrice+$attrPrices;
        return json($price);
    }


}
